//============================================================================
// Name        : cpp_ping.cpp
// Author      : darkflash
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <errno.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "libicmp/libicmp.h"
using namespace std;

#define ERROR(fmt, args...) fprintf(stderr, "%s: " fmt, __progname, ##args)
extern char *__progname;

char *resolve(char *host, char *buf, size_t len)
{
    char *result;
    struct addrinfo *addr;

    if (icmp_resolve(host, &addr))
	return NULL;

    result = icmp_ntoa(addr, buf, len);
    freeaddrinfo(addr);

    return result;
}

int main() {
		size_t len;
		char *addr;
		char buf[80];
		char message[] = "iping: r u there?";
		libicmp_t *isock;

		string ip;
		cout << "input ip: ";
		cin >> ip;

		addr = resolve((char*)ip.c_str(), buf, sizeof(buf));
		if (!addr) {
		ERROR("%s for %s\n", strerror (errno), ip.c_str());
		}

		isock = icmp_open((char*)ip.c_str(), 0x1337, 0);
		if (!isock) {
		ERROR("Failed to open ICMP socket: %s\n", strerror (errno));
		return 0;
		}

		printf("PING %s (%s)\n", ip.c_str(), addr);
		while (1) {
		len = icmp_ping(isock, message, sizeof(message));
		if (!len)
			ERROR("%s for %s\n", strerror (errno), ip.c_str());
		else
			printf("%zd bytes from %s (%s): icmp_req=%d ttl=%d time=%ld.%ld ms\n",
			   len, ip.c_str(), addr, isock->seqno, isock->ttl, isock->triptime / 10, isock->triptime % 10);
		sleep(1);
		}

		icmp_close(isock);

		return 0;
}
